import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;

public class VM_Client_Send implements Runnable
{
  private DataInputStream din;
  private DataOutputStream dout;

  private KeyStore vmKeyStore;         //La nuestra
  private KeyStore emKeyStore;         //La del EM

  private SSLContext sslContext;
  
  static private final String passphrase = "vmpass";

  static private SecureRandom secureRandom;

  static private final String BDuser = "user";
  static private final String BDpassword = "password";
  
  private String idExperiment;
  private String usuari;
  private String empresa;
  private String dadesPath;

  public VM_Client_Send ( String host, int port, String idExperiment, String usuari, String empresa, String dadesPath ) {
    this.idExperiment = idExperiment;
    this.usuari = usuari;
    this.empresa = empresa;
    this.dadesPath = dadesPath;
    connect( host, port );

    new Thread( this ).start(); //Su código aquí
  }

  private void setupServerKeystore() throws GeneralSecurityException, IOException {
    emKeyStore = KeyStore.getInstance( "JKS" );
    emKeyStore.load( new FileInputStream( "em.public" ), 
                        "public".toCharArray() );
  }

  private void setupClientKeyStore() throws GeneralSecurityException, IOException {
    vmKeyStore = KeyStore.getInstance( "JKS" );
    vmKeyStore.load( new FileInputStream( "vm.private" ),
                       passphrase.toCharArray() );
  }

  private void setupSSLContext() throws GeneralSecurityException, IOException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
    tmf.init( emKeyStore );

    KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
    kmf.init( vmKeyStore, passphrase.toCharArray() );

    sslContext = SSLContext.getInstance( "TLS" );
    sslContext.init( kmf.getKeyManagers(),
                     tmf.getTrustManagers(),
                     secureRandom );
  }

  private void connect( String host, int port ) {
    try {
      System.out.println( "Wait while secure random numbers are initialized...." );
      this.secureRandom = new SecureRandom(); 
      this.secureRandom.nextInt();
      System.out.println( "Done." );
      
      setupServerKeystore();
      setupClientKeyStore();
      setupSSLContext();

      SSLSocketFactory sf = sslContext.getSocketFactory();
      SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); 

      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );
    } catch( GeneralSecurityException gse ) {
      gse.printStackTrace();
    } catch( IOException ie ) {
      ie.printStackTrace();
    }
  }

  public void run() {
    //Conexión con la base de datos
    GestorBD gestorbd = new GestorBD();
      
    try{ 
      gestorbd.modificar("vm", BDuser, BDpassword,
      "INSERT INTO vm.EXPERIMENTS values (default, '"+idExperiment+"','"+usuari+"','"+empresa+"','"+dadesPath+"',' ');");

    //Conexión con el Experiment Manager
      dout.writeUTF( idExperiment );
      dout.writeUTF( usuari );
      dout.writeUTF( empresa );
      BufferedReader bin = new BufferedReader(new FileReader(dadesPath));
      String dades;
      while ((dades = bin.readLine()) != null){
	dout.writeUTF(dades);
	
      }
      dout.writeUTF( "Fin!" );
    }
    catch (Exception e){
      e.printStackTrace();
      try { 
	gestorbd.modificar("vm", BDuser, BDpassword, "DELETE FROM vm.EXPERIMENTS WHERE IDEXPERIMENT = '"+idExperiment+"';");
  
      }
      catch (Exception ex){
	ex.printStackTrace();
      
      }
    }
  }
  
}
